var arrayAns = {}; //answers unparsed
var arrayAnsDrop = {}; // parsed answers for drag and drop
var arrayAnsToDrop= {};
var arrayAnsMulti = {};

var notes=[]; // for imgNote
var divs=[]; // divs created by imgNote

var lastFound; // flag to determine if last interaction was successfull
var clickOn; // to determine if a click has been performed on a interactive item
var clickFlag; // flag to store id of a clicked item
var clickObj; // interactive object last clicked on

var feedbackbox; // store id of feedback area
var mouseX, mouseY; //store location of mouse when items are clicked

var completedActivity =false; //boolean
var completedGroup =false; //for groups of questions, to display intermediate feedback
var postponeFinalFB = false; // flag for postponed final feedback, relegated to click binds to call
var initedCount = false; // for feedback purposes, to signal all answers have been counted

//CORRECTIONS
var appliedCorrection = false;

// MULTILANG
var str_verify="";
var str_correct = "";
var str_reinit = "";

//EXO TYPE / MODe HELPER
var exoTypes; //string of types of exercices in this 
var exoType; //array

var exoModes; //string
var exoMode; //array

//VARIATIONS
var mode="";
var suppressCommasAndBreaks = false;

//DEBUG HELPERS
var debugHelper =false;
var debugDispCount = 0;
var debugMode= false;

isExoType = function(type){
	var found = false;
	for(var i=0; i< exoType.length; i++){
		if(exoType[i].toLowerCase() == type.toLowerCase())
			found =true;
	}
	return found;
}

isMode = function(mode){
	var found = false;
	for(var i=0; i< exoMode.length; i++){
		if(exoMode[i].toLowerCase() == mode.toLowerCase())
			found =true;
	}
	return found;
}

getExoType = function(){
	alert(exoTypes);
}

initModes = function(){
	exoModes = $('#mode').text();
	exoMode = exoModes.split(" ");
	suppressCommasAndBreaks = isMode("suppresscommasandbreaks");
	// mode=="suppresscommasandbreaks" ? suppressCommasAndBreaks = true : suppressCommasAndBreaks = false;
}

// $(document).ready(function(){
$(window).load(function(){
	exoTypes= $('#baseType').text();
	exoType = exoTypes.split(" ");
	var toCorrect = false;
	initModes();
	
	if ($('#poem-generator').length > 0){
		$.getScript('/babel-data/scripts/poemgenerator.js',function(){
			loadpoem($("#poem-generator").attr("name")); //loadpoem with lang stored in name attribute	
		});
	}
	
	changeTitle();
	fetchAnswers();
	parseAnswers();
	autoHint();
	initHint();
	initLang();
	initRandom();
	
	for(var i=0; i< exoType.length; i++){
		switch(exoType[i]){
			case "inline" : {
				initInlineExo();
				toCorrect = true;
			}
			break;
			case "fill-in" : {
				initCheckSpelling();
				toCorrect = true;
			}
			break;
			case "directedMatch" : {
				initMultiDrop();
				toCorrect = true;
			}
			break;
			case "directedPair" : {
				initDrop();	
				initTableSort();
				toCorrect = true;
				// alert("directed pair");
			}
			break;
			case "directedPairAbacus" : {
				initDrop();	
				initTableSort();
				toCorrect = true;
			}
			break;
			case "directedPairMatching" : {
				initMatching();
				initDrop();
				toCorrect = true;
			}
			break;
			case "tableSort" : {
				initDrop();	
				initTableSort();
				toCorrect = true;
			}
			break;
			case "matching" : {
				initMatching();
				toCorrect = true;
			}
			break; 
			case "imageMatch" : {
				initImageDrop();
				initDrop();
				toCorrect = true;
			}
			case "onImageMatch" : {
				initOnImageDrop();
				initDrop();
				toCorrect = true;
			}
			break;
			case "multipleChoice" : {
				initMultiChoice();
				toCorrect = true;
			}
			break;
			case "flashMedia" : {
				initParamFlash();
			}
			break;
			case "groupsense" : {
				initGroupSense();
				toCorrect = true;
			}
			break;
			case "stressedVowel" : {
				initStressedVowel();
				toCorrect = true;
			}
			break;
			case "findWords" : {
				findWord();
				toCorrect = true;
			}
			break;
		}
	}
	
	if(toCorrect) initCorrectForm();
	
	initReinitForm();
	 // TO REORDER
	
	initFB();
	initMovable();
	
	
	clarify();
	// switchAddr();
	beautify();
	iefix();
	watchAnswerGroups();
	
});

// ************* BEGIN TWEAKS *************
beautify = function(){
	$(".prompt").css('opacity', 0.7);
	$("<span class='positive'/>").remove();
	$(".notCurrentSubPool").css('opacity', 0.5);
	if( $(".repoz").length > 0)
		repositionElements();
	if( isExoType("imageMatch"))
		$('.note').css("min-width", '45px');
}

shuffle = function(input){
	var len = input.length;
	//var usedpos = {};
	var shuffled = input;
	var splitters = ['m','n','o','b','c','d','u','v','w','e','f','a','g','h','i','p','q','r','s','j','k','l','t','x','y','z'];
	var assembled="";
	// debugThis(splitters);
	
	for (var i = 0; i < splitters.length+1; i++){
		var splitted = shuffled.split( splitters[i] );
		
		for (var j=0; j< splitted.length ; j++){
			assembled += splitted[j];
			// debugThis("splitter="+splitters[i]+ " splitted=" + splitted[j] + " assembled=" + assembled, 10);
		}
		for (var k=1; k < splitted.length && input.indexOf(splitters[i])>= 0; k++){
			if(k % 2==0) assembled +=splitters[i];
			else assembled = splitters[i] + assembled;
		}
		shuffled= assembled;
		assembled=""
	}
	return shuffled;
	
	// while (shuffled.length != len){
	// 		var ranpos = Math.floor(Math.random()*len +1);
	// 		if ( !usedpos[ranpos]){
	// 			usedpos[ranpos] = true;
	// 			shuffled += input[ranpos];
	// 		}
	// 	}
}

autoHint = function(){
	/* FOR FILL IN INTERACTIONS */
	$(".autohint").each(function(){
		var key = $(this).attr('name');
		var refkey = "for"+key;
		var ans;
		if( isExoType("fill-in") )
		 	ans = (arrayAnsDrop[ $("#"+key).attr('id') ] ).toLowerCase();
		else
			ans = $( "#" +arrayAnsDrop[ $("#"+key).attr('id') ] ).text();
		// debugThis(ans);
		var texthint;
		if( !$(this).is(".shuffle"))
			texthint = ans.replace(/\_/g," ").substring(0, 2+(ans.length)/4 )+"...";
		else
			texthint  =  shuffle(ans.replace(/\_/g," "));
		// debugThis(texthint);
		$(this).html("<a href='' name='"+refkey+"' class='bwhint'>?</a><span class='invisible' id='"+refkey+"'>"+texthint+"</span>");
	});
}

changeTitle = function(){    
	var oldTitle  = document.title;
	document.title = $("#exotitle").text() != "" ? $("#exotitle").text() + " - Babelweb" : oldTitle;
}

iefix = function(){
	// $("img").each(function(){
	// 		// alert( $(this).attr('height') );
	// 		if( $(this).attr('height')=="5px" ){
	// 			
	// 			$(this).attr('height', '100px');
	// 		}
	// 	});
	
	if ($.browser.msie && $.browser.version.substr(0,1)<7 ) {
		$(".block, .block-i").each(function(){		
			var assignWidth = 0;
			var numChars = $(this).text().length;
			assignWidth = numChars * 3;
			assignWidth > 200 ? assignWidth = 200 : true;
			// alert("recal "+ assignWidth);
			$(this).css({width : assignWidth+"px"});
		});
		$(".note").css({width:"45px"});
		$(".blocksize").css({width:"100px"});
	}
	if ($.browser.msie && $.browser.version.substr(0,1)<=7) {
		$(".drop-camo").not(".note").not( $(this).parent().is("td") ).css({width:"100px"});
	}
}

/*
repositionElements = function(){
	$("div.exos ").append("<div class='dynreposition' id='dynreposition'></div>");
	var numRepoz = $(".repoz").length;
	var counterDoneRepo = 0;
	var widthExo = $("div.exos").width();
	var usedSpace = 0;
	var margin = 10;
	var wrapperId;
	// alert("exo:"+ widthExo);
	$('.repoz').each(function(){
		var repo_w=$(this).width();
		if(repo_w >= widthExo/2){
			pos1 = $("table", this).width();
			pos2 = $("img", this).width();
			
			pos1 > pos2? repo_w = pos1 : repo_w = pos2;
			repo_w += margin;
		}
		if(repo_w == 0)
			repo_w= 200;
		// alert("repo_w: "+counterDoneRepo +" "+repo_w);
		var elmRepo = $(this).clone();
		if(counterDoneRepo==0 || counterDoneRepo %2 == 0){ //$(this).css({width:repo_w+"px", float:"left"});
			$(this).css({width:repo_w+"px", float:"left"});
			usedSpace += repo_w;
			counterDoneRepo++;
			wrapperId= "wrapper"+counterDoneRepo;
			$("#dynrepoz").append("<div class='wrapperRepoz' id="+wrapperId+"></div>")
		}
		else{
			var newWidth = widthExo-usedSpace - margin ;
			usedSpace += newWidth;
			counterDoneRepo++;
			// alert("new width "+newWidth);
			$(this).css({width: newWidth+"px", float:"left"});
			
		}
		
		$(this).appendTo("#"+wrapperId);
		if(counterDoneRepo %2 == 0){
			usedSpace = 0;
			$("#dynrepoz").append("<br style='clear:both;'/>");
		}
	});
	// $("#dynrepoz").css({margin:"10px 0px"});
	$("#fbholder").appendTo("#dynrepoz").css({clear:"both", margin:"15px 0 0 0"});
	$("#correction").appendTo("#dynrepoz").css({clear:"both", margin:" 15px 0 0 0"});
}
*/

repositionElements = function(){
        $("div.exos ").append("<div class='dynreposition' id='dynrepoz'></div>");
        var numRepoz = $(".repoz").length;
		var counterDoneRepo = 0;
		var widthExo = $("div.exos").width();
		var usedSpace = 0;
		var margin = 10;
		var wrapperId;
        // alert("exo:"+ widthExo);
        $('.repoz').each(function(){
                var repo_w=$(this).width();
                if(repo_w >= widthExo/2){
					pos1 = $("table", this).width();
					pos2 = $("img", this).width();

					pos1 > pos2? repo_w = pos1 : repo_w = pos2;
					repo_w += margin;
				}
                if(repo_w == 0)
                        repo_w= 200;
                // alert("repo_w: "+counterDoneRepo +" "+repo_w);
                var elmRepo = $(this).clone();
                if(counterDoneRepo==0 || counterDoneRepo %2 == 0){ //$(this).css({width:repo_w+"px", float:"left"});
                        $(this).css({width:repo_w+"px", float:"left"});
                        usedSpace += repo_w;
                        counterDoneRepo++;
                        wrapperId= "wrapper"+counterDoneRepo;
                        $("#dynrepoz").append("<div class='wrapperRepoz' id="+wrapperId+"></div>")
                }
                else{
                        var newWidth = widthExo-usedSpace - margin;
                        usedSpace += newWidth;
                        counterDoneRepo++;
                        // alert("new width "+newWidth);
                        $(this).css({width: newWidth+"px", float:"left"});
                        
                }
                
                $(this).appendTo("#"+wrapperId);
                if(counterDoneRepo %2 == 0){
                        usedSpace = 0;
                        $("#dynrepoz").append("<br style='clear:both;'/>");
                }
        });
        // $("#dynrepoz").css({margin:"10px 0px"});
        $("#fbholder").appendTo("#dynrepoz").css({clear:"both", margin:"15px 0 0 0"});
		$("#correction").appendTo("#dynrepoz").css({clear:"both", margin:" 15px 0 0 0"});
		$(".bottom-nav").appendTo("#dynrepoz").css({clear:"both", margin:" 15px 0 0 0"});
		
}


// iefix = function(){
// 	if($.browser.msie && $.browser.version=="6.0"){
// 		$(".block, .block-i, .block-h").css(width:"50px");
// 	}
// }

switchAddr = function(){
	$("object").each(function(){
		if( $(this).attr("type")=="application/x-shockwave-flash"){
			$("param", this).each(function(){
				if($(this).attr('name')=="FlashVars"){
					// alert("found");
					var addr = $(this).attr("value");
					var modAddr = addr.split("mp3=")[1];
					$(this).attr("value", "http://labas.com"+modAddr);
				}
			});
		}
	});
}

clarify = function(){
	var perline = 10;
	var numSpans = $('#global > .exos').find("span").length;
	var tmp = perline;
	while(tmp < numSpans && isExoType('directedPairAbacus')){
		$('#global > .exos').find("span:nth-child("+tmp+")").after("<br/><br/>");
		tmp+=perline;
	}
	if( $(".answergroup").find("*[name ^= 'for-']").length > 0){
		$(".answergroup").find("*[name ^= 'for-']").each(function(){
			if( $(this).prev("p").is(".repoz") ){
				$(this).appendTo($(this).prev("p"));
			}
		});
	}
}

initLang = function(){
	if($('#lang').text()=="fr"){
		str_verify="Vérifier";
		str_correct = "Corrigé";
		str_reinit = "Réinitialiser";
	}
	if($('#lang').text()=="es"){
		str_verify="Revisa";
		str_correct = "Corrige";
		str_reinit = "Reset";
	}
	if($('#lang').text()=="it"){
		str_verify="Controllo";
		str_correct = "Soluzione";
		str_reinit = "Reset";
	}
}

// ************* END TWEAKS *************

initFB = function(){
	if($('#feedbackType').text()=="float")
		floatFB();
	
	if($('#feedbackType').text()=="bottom")
		bottomFB();
	
	feedbackbox="#fb";
}

initCorrectForm = function(){
	if( $('.globalFB').length>0 && $('.globalFBNeg').length>0)
		$('#correction').append('<form id="verification" method="get" action="">'+
							'<input name="verification" value="'+str_verify+'" onclick="" type="submit"/>'+
							'</form>');
	if(!isMode("nocorrection"))
		$('#correction').append('<form id="correct" method="get" action="">'+
							'<input name="correction" value="'+str_correct+'" onclick="" type="submit"/>'+
							'</form>');
	
	
	initCorrection();
	initVerification();
}

initReinitForm = function(){
	if($('#baseType').text()!="" && $('#baseType').text()!="none")
		$('#correction').append('<form id="reinit" method="get" action="">'+
									'<input name="reinit" value="'+str_reinit+'" onclick="window.location.reload()" type="submit"/>'+
							'</form>');
}

/************** ANSWER WATCHING HELPERS ***************/

isCorrectMulti = function(){
	if(!isExoType("multipleChoice")) return true;
	var t = $('.multi').length == $('.multiItem.success').length;
	// if(debugMode) alert("multis:"+$('span.multi').length + " success="+$('.multiItem.success').length);
	if(t && debugMode) alert("completed code multi");
	return t;
}

isCorrectInline = function(){
	if(!isExoType('inline')) return true;
	var t = $('.inline-exe').length == $('.success').length; // && $('.inline-exe').length != 0
	if(t && debugMode) alert("completed code inline");
	return t; 
}

isCorrectFillin = function(){
	if(!isExoType("fill-in")) return true;
	var t = $('.gap').length == $('.fillin.success').length; // && $('.gap').length != 0
	if(t && debugMode) alert("completed code fill-in");
	return t; 
}

isCorrectGroupSense = function(){
	if(!isExoType("groupsense")) return true;
	var t = $(".senseseparator").find('.feedback[name="true"]').length == $(".senseseparator-found").length;
	if(t && debugMode) alert("completed code groupsense");
	return t;
}

isCorrectStressedVowel = function(){
	if(!isExoType("stressedVowel")) return true;
	var t = $(".stressedvowel").find('span[name="true"]').length == $(".stressedvowel-found").length;
	if(t && debugMode) alert("completed code stressedvowel");
	return t;
}

isCorrectFindWords = function(){
	if(!isExoType("findwords")) return true;
	var t = $(".findme").length == $(".findme:has('found')").length;
	if(t && debugMode) alert("completed code findwords");
	return t;
}

isCorrectMatching = function(){
	if(!isExoType("matching")) return true;
	var t =$('.matchend').length == ($('.found').length)/2;
	if(t && debugMode) alert("completed code matching");
	return t;
}

isCorrectMultiDrop = function(){
	return isCorrectDND();
}

isCorrectDND = function(){
	if(!isExoType("directedMatch") && !isExoType("directedPair") && !isExoType("directedPairAbacus") && !isExoType("directedPairMatching") && !isExoType("imageMatch") && !isExoType("onImageMatch") && !isExoType("tableSort")  ){
		return true;
	}
	var done=false;
	$('body').each(function(){ //HACKED, initially .exos
		var totalNumAns;
		if(!initedCount){
			totalNumAns = $(this).find('.ui-draggable:not(.ui-droppable .ui-draggable)',this).not(".used").length ;
			$(this).attr('totalNumAns', totalNumAns);
			initedCount = true;
		}
		else{
			totalNumAns = $(this).attr('totalNumAns');
		}
		var totalUsed = $(this).find('.used',this).length;
		//alert("dnd total="+totalNumAns+ " used="+totalUsed);
		if(totalNumAns == totalUsed ){
			if(debugMode) alert("completed code dnd");
			done=true;
		}
	});
	return done;
}

checkFBTableSort = function(){
	$('.batchsort').each(function(){
		if(!$(this).attr("finished")) $(this).attr("finished",0);
		var numAns = $(this).find('span.ui-draggable',this).length;
		var used = $(this).find('span.used',this).length;
		if(numAns == used && used != 0 ){ //|| numAns == 0 FIXING ?
			var t= parseInt($(this).attr("finished"));
			if(t==0){
				$(this).append("<p class='positive'>"+$('.positive',this).text()+"</p>" ).hide().fadeIn("slow");
				$(this).attr("finished",1);
			}
		} 
		return;
	});
	return true;
}


watchAnswerGroups= function(){
	// if(debugMode) alert("called to check answers");
	$('.answergroup').each(function(){
		var numAns = $(this).find('span.block',this).length;
		var used = $(this).find('span.used',this).length;
		// alert("ans for this group : " + numAns + "    used: "+ used);
		if(numAns == used && used != 0 ){ //|| numAns == 0 FIXING ?
			//$(this).parent().find('.feedback').removeClass('invisible');
			completedGroup=true;
			//completedActivity=true;
			// alert("completed code1, numAns="+numAns+" used="+used);
		} 
	});
	
	var t1=isCorrectDND();
	var t2=isCorrectMulti();
	var t3=isCorrectInline();
	var t4=isCorrectFillin();
	var t5=isCorrectMatching();
	var t6=isCorrectGroupSense();
	var t7=isCorrectFindWords();
	var t8=isCorrectStressedVowel();
	// alert("t1="+t1+" t2="+t2+" t3="+t3+" t4="+t4+" t5="+t5);
	if(t1 && t2 && t3 && t4 && t5 && t6 && t7 && t8){
		completedActivity=true;
		finalFeedback();
	}
	
	checkFBTableSort();
	/*
	$('.exos').each(function(){
		var totalNumAns;
		if(!initedCount){
			totalNumAns = $(this).find('.ui-draggable',this).length ;
			$(this).attr('totalNumAns', totalNumAns);
			initedCount = true;
		}
		else{
			totalNumAns = $(this).attr('totalNumAns');
		}
		var totalUsed = $(this).find('.used',this).length;
		
		// alert('ans='+totalNumAns+" used="+totalUsed);
		if(totalNumAns == totalUsed && totalUsed != 0 || totalNumAns == 0
				&& isExoType("inline") && isExoType("fill-in") && isExoType("matching")){
			// alert("ended");
			$(this).parent().find('.feedback').removeClass('invisible');
			completedActivity=true;
			// alert("completed code2");
			finalFeedback();
		}
	});
	
	if( $('.inline-exe').length == $('.success').length && $('.inline-exe').length != 0){
		// $(".globalFB").removeClass("invisible");
		completedActivity=true;
		// alert("completed code3");
		finalFeedback();
	}
	
	if( $('.gap').length == $('.success').length && $('.gap').length != 0){
		// $(".globalFB").removeClass("invisible");
		completedActivity=true;
		// alert("completed code4");
		finalFeedback();
	}
	
	if(isExoType("matching")){
		if( $('.matchend').length == ($('.found').length)/2 ){
			// alert( "ends="+$('.matchend').length + " found="+$('.found').length);
			completedActivity=true;
			finalFeedback();
		}
	}
	*/
	
}

finalFeedback = function(){
	if(!completedActivity){
		// $('object').hide();
		// 		$('.inputbox').hide();
		if($(".globalFBNeg").length!=0){
			if(clickOn){
				postponeFinalFB = true;
			}
			else{
				centerPopup(".globalFBNeg");  
				loadPopup(".globalFBNeg");
			}
		}
	}
	else if($(".globalFB").length!=0){
		// $('object').hide();
		if(clickOn){
			postponeFinalFB = true;
		}
		else{
			centerPopup(".globalFB");  
			loadPopup(".globalFB");
		}
	}
	
}

feedback = function(content, state){
	$('span.positive, span.negative').each(function(){
		$(this).addClass('invisible');
	});
	initHint();
	var noanim=false;
	
	if(!content){
		noanim=true;
		content="";
	}
	
	$(feedbackbox).html("<p>"+ content +"</p>");
	
	if(state){
		if(!noanim) $(feedbackbox).effect('bounce');
		$(feedbackbox).removeClass("negFBB");
		$(feedbackbox).addClass("posFBB");
	}
	else if(!state){
		if(!noanim) $(feedbackbox).effect('shake');
		$(feedbackbox).removeClass("posFBB");
		$(feedbackbox).addClass("negFBB");
	}
	
}

floatFB = function(){
	$('.listing').append("<tr style='height:30px; overflow:visible;'><td colspan='3'><div id='fb' class='staticFBbox'></div></td></tr>");
	// $('.exos').append("<div id='fb' class='staticFBbox'></div>");
	// var pos = $(window).height();
	// $('#fb').css({top: pos-150 + 'px'});
}

bottomFB = function(){
	$('.exos').append("<div id='fbholder'><p id='fb' class='feedback-area'></p></div>");
}

fetchAnswers = function(){
	$("div.answer-set").find('li').each(function() { 
		var tmp= $(this).text();
  		arrayAns[tmp] = tmp;
	});
	
}

jQuery.fn.sort = function() {
        return this.pushStack( jQuery.makeArray( [].sort.apply( this, arguments ) ) );

};

initRandom = function(){
	$('.random').children().sort(function(a, b) { 
		var rand=Math.floor(Math.random()*2) - Math.floor(Math.random()*2);
		return rand;
	}).prependTo('#answergroup'); 
	
	for(var i=0; i< $("#answergroup").children().size(); i++){
		if(i%6==0)
			$("#answergroup").find(":nth-child("+i+")").after("<br/>");
	}	// 
		// 
		// $("#answergroup").find("span:nth-child(5)").after("<br/>");
		// $("#answergroup").find("span:nth-child(10)").after("<br/>");
	

}

initHint = function(){
	//non persistent hover
	$("a.bwhint").tooltip({ 
    	bodyHandler: function() { 
        	return $("#"+$(this).attr("name")).html(); 
    	}, 
	    showURL: false 
	})
	.click(function(){return false;})
	.html("<img src='/babel-data/images/assets/help-small.gif' alt='?'/>");
	
	$("a.img-hint").each(function(){
		var putTop = -($("#"+$(this).attr("name")).height()/4);
		$(this)
		.tooltip({ 
			delay:0,
	    	bodyHandler: function() { 
	        	return $("#"+$(this).attr("name")).html(); 
	    	},
			track: false,
			top: putTop,
			left: 5,
		    showURL: false
		})
		.click(function(){return false;});
	});
	
	
	//semi persistent hover
	$("a.initHoverNoAutoClose").each(function(){
		var id= "#"+$(this).attr("name");
		$(this).jHelperTip({
	 		trigger: "click", 
	 		dC: id,
			autoClose: false,
	 		opacity: 0.9
	 		
		});
		$(this).click(function(){return false;});
		// .click(function(){return false;});
	});
	
	//persistent popup window
	$(".hover-content, .globalFB, .globalFBNeg").prepend("<a class='popupContactClose jHelperTipClose'>x</a>  ");
	
	$("a.initHover").click(function(){  
		centerPopup("#"+$(this).attr("name"));  
		loadPopup("#"+$(this).attr("name")); 
		return false;
	});

	//CLOSING POPUP
	//Click the x event
	$(".popupContactClose").click(function(){
		disablePopup(currentPopup);
		return false;
	});
	
	$(".jHelperTipClose").click(function(){
		$(".hover-content").hide();
	})	
	
	//Click out event
	$("#backgroundPopup").click(function(){
		disablePopup(currentPopup);
		return false;
	});
	//Press Escape event
	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus==1){
			disablePopup(currentPopup);
		}
	});
}

initMovable = function(){
	var pos = $(window).height();
	$('.movable').css({top: pos-450 + 'px', position:"fixed"});
	// $('.movable').draggable({revert:false, 
	// 						cursor: 'move'});
}

/**************************************
// answer parsing
/**************************************/

parseAnswers= function(){
	for(var key in arrayAns){
		var tmp_array= key.split(" "); //gives an array with 2+ items : key value
		
		arrayAnsToDrop[tmp_array[0]] = "";
		
		for(i=1; i<tmp_array.length; i++){ // this is done in case of multiple placements (drop zones) for one answer
			if(!arrayAnsDrop[tmp_array[i]])
				arrayAnsDrop[tmp_array[i]]= ""; //initialize space
				
			arrayAnsDrop[tmp_array[i]] += tmp_array[0] +" "; // drop zone(s) -> answer-id
			
			arrayAnsToDrop[tmp_array[0]] += tmp_array[i]; i==tmp_array.length-1? true : arrayAnsToDrop[tmp_array[0]] += "&";  //  answer-id -> drop zone(s) 
			// adds one more space and requires parsing
		}
	}
}


/**************************************
// inline and correction
/**************************************/
randomizeInlineExo = function(){	
	$(".inline-exe").each(function(){   
		$(this).sortOptions();
		$(this).children().filter(function(){
			return $(this).attr("value")==-1;
		});
	});}

initInlineExo = function(){
	randomizeInlineExo();
	arrayAnsIn= fetchAnswersIEf();
	
	$(".inline-exe").change( function(){
			var answer = $(this).selectedValues();
			// alert("-"+arrayAnsIn[answer]+"-");
			if(answer=='-1'){
				doNeutral($(this));
				//feedback("", null);
			}	
			else{
				var found = false;
				for(value in arrayAnsIn){
					if(arrayAnsIn[value] == answer){
						var content = $(this).next('.feedback').find(".positive").html();
						feedback(content, true);
						doSuccess($(this));
						found = true;
					}
				}
				if(!found){
					var content = $(this).next('.feedback').find(".negative").html();
					var contentPerItem;
					if( $("span[name='"+answer+"']").size !=0 ){
						contentPerItem=$("span[name="+answer+"]").html();
					}
					if(contentPerItem != null)
					content=contentPerItem;
					feedback(content, false);
					doFail($(this));
				}
				$(this).blur();
			}

			$(this).blur();
			watchAnswerGroups();
	});
}

fetchAnswersIEf = function(){
	arrayAnsIn = [];
	$("div.answer-set").find('li').each(function() { 
		var tmp= $(this).text().split(" ")[0];
  		arrayAnsIn.push(tmp);
	});
	return arrayAnsIn;
}

correctInline = function(){
	var once=false;
	var one=false;
	$(".inline-exe:not(.success)").each(function(){
			arrayAnsIn= fetchAnswersIEf();
			var answer;
			$('option', this).each(function(){
				var val = $(this).val().split(" ")[0];
			
				for(i in arrayAnsIn){
					if(arrayAnsIn[i]==val){
						// alert($(this).text());
						answer=$(this).text();
						// $(this).parent().next('span').removeClass('invisible').addClass('corrected').text(answer);
						$(this).parent().parent().addClass('corrected').text(answer);
					}
				}
			});
			$(this).remove();
		});
}

/**************************************
// multi choice
/**************************************/

initMultiChoice = function(){
	$('.multi :input').click(function(){
		$(this).parent().find('input').each(function(){
			$(this).parent().parent().find('.fail').removeClass('fail');
			$(this).parent().parent().find('.success').removeClass('success');
			//doNeutral($(this).parent());
		});
		// alert("::"+arrayAns[$(this).attr('id')]+"::" );
		var arrayAnsIn= fetchAnswersIEf();
		var found=false;
		for(i in arrayAnsIn)
			if(arrayAnsIn[i]==$(this).attr('id'))
				found= true;
		
		if(found) { // arrayAns[$(this).attr('id')] == $(this).attr('id') ){
			doSuccess($(this).parent());
			feedback($(this).parent().parent().find('.positive').html(), true);
		}
		else{
			doFail($(this).parent());
			// if(!found){
			// 				var content = $(this).next('.feedback').find(".negative").html();
			// 				var contentPerItem;
			// 				if( $("span[name='"+answer+"']").size !=0 ){
			// 						contentPerItem=$("span[name="+answer+"]").html();
			// 					}
			// 				if(contentPerItem != null)
			// 					content=contentPerItem;
			// 				feedback(content, false);
			// 				doFail($(this));
			// 			}
			// 			$(this).blur();
			var content = $(this).parent().parent().find(".feedback .negative").html();
			var contentPerItem;
			
			if( $("span[name='"+$(this).attr('id')+"']").length !=0 ){
				contentPerItem = $("span[name='"+$(this).attr('id')+"']").html();
				// alert("narf");
			}
			if(contentPerItem != null)
				content= contentPerItem;
			//else feedback($(this).parent().find('.negative').html(), false);
			feedback(content, false);
		}
		watchAnswerGroups();
		
	});
}

/*correctMultiChoice = function(){
        for(var key in arrayAns){
                $('input#'+key+':not(.success)').each(function(){
                        // alert("found");
                        $(this).select();
                        $(this).parent().addClass("corrected");
                });
        }
}*/


correctMultiChoice = function(){
	var arrayAnsInC= fetchAnswersIEf();
	for(i in arrayAnsInC){
		var tmp = arrayAnsInC[i];
	// for(var key in arrayAns){
		$('input#'+tmp+':not(.success)').each(function(){
			// alert("found");
			// $(this).select();
			$(this).parent().addClass("corrected");
		});
	}
}

/**************************************
// drag and drop
/**************************************/

initDropCommon = function(){
	$(".block").draggable({revert:true, 
							distance: 20, 
							cursor: 'crosshair', 
							cursorAt : {top : 5, left : 5}
							}); 
	
 	$(".block-i, .block-h").draggable({revert:true, 
							distance: 20, 
							helper: 'clone', 
							// appendTo: 'body', 
							cursor: 'crosshair', 
							cursorAt : {top : 5, left : 5}
							})
							.each(function(){
								if ($.browser.msie){ // && $(this.find('img').length>0) ){
									//$(this).prepend("<span class='ongrey'>&#160;&#160;&#160;&#160;&#160;</span>");
								}
							})
							/*.each(function(){
								if( $("img",this).length>0){
									var newId= "for"+$(this).attr("id");
									$(this).append("<span id='"+newId+"'></span>")
									var src = $("img",this).attr("src");
									// debugThis(src);
									// $(this).css('background-image','url('+src+')');
									// $("#"+newId).css({background : "#FF0000 url("+src+") no-repeat top left", width: "250px"});
									// $("img",this).remove();
								}
							})*/
							;
							
	/*if(isExoType("directedMatch"))
		$(".block, .block-i, .block-h").each(function(){
			var id = $(this).attr('id');
			var targetCount = arrayAnsToDrop[id].split("&").length;
			$(this).attr('targetCount', targetCount);
			$(this).attr('dropCount', 0);
			$(this).attr('dropSpots', "");
		});*/
	
	if(isExoType("directedMatch"))
		$(".block, .block-i, .block-h").each(function(){
			var id = $(this).attr('id');
			var targetCount = arrayAnsToDrop[id].split("&").length;
			$(this).attr('targetCount', targetCount);
			$(this).attr('dropCount', 0);
			$(this).attr('dropSpots', new String());
		});
}

initDrop = function(){
    initDropCommon();
	initFBDND();
    var droppable = $(".drop, .drop-camo");
    // alert("drop");
	$(".drop:not([id ^= 'fake'])").each( function(){
		var acceptRaw = arrayAnsDrop[ $(this).attr('id')];
		// debugThis(acceptRaw, 14);
		var acceptSplit = acceptRaw.split(" ");
		// alert(acceptSplit);
		var accept_str = "";
		for(var i=0;i <acceptSplit.length - 1; i++){
			accept_str+="#"+acceptSplit[i]+ ", ."+acceptSplit[i]+ ", ";
		}
		// debugThis(accept_str, 3);
		$(this).droppable({
			accept: accept_str,
			tolerance: "pointer",
			activeClass: 'droppable-active',
			hoverClass: 'droppable-hover',
			drop: function(ev,ui) {
					$(this).empty();	
					//BEGIN TWEAK FEEDBACK APPEARING IN DRAGGABLE BLOCKS
					ui.draggable.find('.feedback').css({display:"none"});
					$(".block").find('.feedback').css({display:"none"});
					//END TWEAK
					//REMOVE SURROUNDING DROPPABLE BLOCK AND ADD ELEMENT
					$(this).after(ui.draggable).remove();
					ui.draggable.addClass('used');
					// $(this).parent().css({width: "auto"});
					lastFound=true;
					watchAnswerGroups();
			}
		})
	});
	
	$(".drop-camo").each( function(){
		var ans_accepted = "";
		var count = 0;
		var separator="";
		// alert("drop-camo");
		if(arrayAnsDrop[$(this).attr('id')]){
			var ans_dropzone = arrayAnsDrop[$(this).attr('id')].split(" ");
			for(i=0; i < ans_dropzone.length - 1; i++  )
				ans_accepted+=  "#"+ans_dropzone[i]+", ";
		}
		//var ans_accepted = "."+arrayAnsDrop[$(this).attr('id').split(" ")];
		$(this).droppable({
			accept: ans_accepted,
			tolerance: "pointer",
			activeClass: 'droppable-active',
			hoverClass: 'droppable-hover',
			drop: function(ev,ui) {
				if( !isExoType("tableSort") && !isExoType("directedPairAbacus") 
					&& $('#mode').text()!="single"  
				){
					// alert("1st type");getExoType();
					var object = ui.draggable.clone();
					object.draggable('disable');
					object.css({position:'relative'});
					//BEGIN TWEAK FOR FEEDBACK APPEARING IN DRAGGABLE BLOCKS
					object.find('.feedback').css({display:"none"});
					$(".block-i").find('.feedback').css({display:"none"});
					//END TWEAK
					
					if(count==0) separator=""; 
					else if(count%4==0 && !suppressCommasAndBreaks) 
						separator=",<br/><br/>"; 
					else if(!suppressCommasAndBreaks)
						separator=", ";
						
					count++;
					$(this).append(separator)
					$(this).append(object);
					
					ui.draggable.draggable('disable');
					ui.draggable.draggable('option', 'revert', false);
					ui.draggable.addClass('used');
					ui.draggable.removeClass('block');
					if( object.is(".block-h"))
						object.css({background:"#fff"})
					lastFound=true;
					watchAnswerGroups();
				}else{
					// alert("2nd type");getExoType();
					$(this).append(ui.draggable);
					if(isExoType("directedPairAbacus"))
						$(this).append("<br/><br/>");
					ui.draggable.draggable('disable');
					// ui.draggable.draggable('option', 'revert', false);
					ui.draggable.addClass('used');
					ui.draggable.removeClass('block');
					
					lastFound=true;
					watchAnswerGroups();
				}
				if($(this).is(".note")){
					// var blocklen = ui.draggable.width()+8;
					// var blockheight = ui.draggable.height();
					// $(this).css({width: blocklen +"px", height: blockheight+"px", border: "none"});
					$(this).css({border: "none", overflow:"visible"});
					// debugThis(spanlen);
				}
			}
		})
	});
}

correctMultiDrop = function(){
	var counter = 2;
	var done=false;
	for (key in arrayAnsDrop){
		if(key!="" && key!=null){
			var ansForKey = (arrayAnsDrop[key]).split(" ");
			var it =0; // counter to know when to skip line
			for (var pos = 0 ; pos< ansForKey.length; pos++){ //multiple possible answers
				it+=1;
				ans= ansForKey[pos];

				if( ans!="" && !$('#'+ans).is('.used')){
					var dropSpots = $('#'+ans).attr('dropSpots').toString();
					var dropCount = parseInt($('#'+ans).attr('dropCount'));
					var targetCount = parseInt($('#'+ans).attr('targetCount'));
					var arrayDropSpots = dropSpots.split("&");
					var foundSpot = false;
					
					// debugThis("key="+key+" ans="+ans+" dropcount="+dropCount+" t\nargetcount="+targetCount+" \spots="+dropSpots);
					for(var j=0; j<arrayDropSpots.length; j++) if(arrayDropSpots[j]==key) foundSpot=true;

					if(!foundSpot){
						dropCount++;
						$('#'+ans).attr('dropCount', dropCount);
						
						$("#"+key).append( '<span class="corrected">'+$('#'+ans)
							.html() + "</span>&nbsp;&nbsp;")
							.append( it%counter==0 ? "<br/><br/>" : "");
							
						targetCount==dropCount ? 
							$('#'+ans).addClass('usedCorrection').draggable("disable") 
							: $('#'+ans).addClass('semiUsed');
					}
				}
			}
		}
	}
}

correctDrop = function(){
	var counter = 4;
	if($("#feedbackType").text()=="float") counter=2;
	
	for (var key in arrayAnsDrop){
		if(key!="" && key!=null){
			if($("#"+key).text()==".........."){ // exercices with gaps, remove dots
				$("#"+key).html("");
				counter=1000;
			}

			var ansForKey = (arrayAnsDrop[key]).split(" ");
			var it =0; // counter to know when to skip line
			for (var pos = 0 ; pos< ansForKey.length; pos++){
				it+=1;
				ans= ansForKey[pos];
				if( ans!="" && ans!=null && !$('#'+ans).is('.used')){
					// debugThis("appending answer");                    
					if( $('#'+ans).is('img') ){
						var im = new Image();
						im.src=$('#'+ans).attr('src');  
						im.title=$('#'+ans).attr('title');  
						im.alt=$('#'+ans).attr('alt');   
						im.alt=$('#'+ans).attr('class')+" corrected"; 
						$("#"+key).append(im);
					}
					else
						$("#"+key).append(    
							($("#"+key).is(".blocksize")? '<br/>' : '' ) + '<span class="corrected">'+$('#'+ans).html()+ "</span>");
						
						
					$("#"+key)
					//.append(    
						//($("#"+key).is(".blocksize")? '<br/>' : '' ) + '<span class="corrected">'+resAns+ "</span>")
						
						//($("#"+key).is(".blocksize")? '<br/>' : '' ) + '<span class="corrected">'+$('#'+ans).html() + "</span>")
					.append( it%counter==0 ? "<br/><br/>" : "");
					if( $("#"+key).is(".note") ){
						$("#"+key).css({border: "none", overflow:"visible"});
					}
					$('#'+ans).addClass('usedCorrection').draggable("disable");
				}
			}
		}
	}
	$("span.feedback").remove();	
}

/**
	initialises feedback for drag and drop items
*/
initFBDND = function(){
	// $('.block').bind('dragstart', function(ev, ui) {
	//   	$(ui).attr('found', 'false');
	// 	clickOn=true;
	// 	lastFound=false; // <reset> flag to determine if last object was correctly placed, for feedback purposes
	// });
	// 
	// $('.block').bind('dragstop', function(ev, ui) {
	//   	if(!lastFound) feedback( $(".negative", this ).html() , false);
	// 		else feedback( $(".positive", this ).html() , true);
	// 	clickOn=false;
	// 	if(postponeFinalFB){
	// 		finalFeedback();
	// 		postponeFinalFB= false;
	// 	}
	// });
	
	$('.block, .block-i, .block-h').bind('dragstart', function(ev, ui) {
	  	$(ui).attr('found', 'false');
		clickOn=true;
		lastFound=false; // flag to determine if last object was correctly placed, for feedback purposes
	});

	$('.block, .block-i, .block-h').bind('dragstop', function(ev, ui) {
	  	if(!lastFound) feedback( $(".negative", this ).html() , false);
	  	else feedback( $(".positive", this ).html() , true);
		clickOn=false;
		if(postponeFinalFB){ // fix for fb window not appearing while animation ongoing 
			finalFeedback();
			postponeFinalFB= false;
		}
	});
}

initMultiDrop = function(){
	
    initDropCommon();
	//alert("multi drop");
	initFBDND();

	$(".drop-camo").each( function(){
		var count = 0;
		var ans_accepted = "";
		var separator="";
		var currentId= $(this).attr('id');
		if(arrayAnsDrop[$(this).attr('id')]){
			var ans_dropzone = arrayAnsDrop[currentId].split(" ");
			for(i=0; i < ans_dropzone.length - 1; i++  )
				ans_accepted+="#"+ans_dropzone[i]+", ";
		}
		//alert(ans_accepted);
		$(this).droppable({
			accept: ans_accepted,
			tolerance: "pointer",
			activeClass: 'droppable-active',
			hoverClass: 'droppable-hover',
			drop: function(ev,ui) {
				var dropCount;
				var targetCount;
				var dropSpots = ui.draggable.attr('dropSpots');
				var arrayDropSpots = dropSpots.split("&");
				var foundSpot = false;
				for(var i=0; i<arrayDropSpots.length; i++) if(arrayDropSpots[i]==currentId) foundSpot=true;
				lastFound=true;
				
				if(!foundSpot){
					dropSpots+=currentId+"&";
					dropCount = parseInt(ui.draggable.attr('dropCount')) + 1;
					targetCount = parseInt(ui.draggable.attr('targetCount'));
					
					ui.draggable.attr('dropCount', dropCount);
					ui.draggable.attr('dropSpots', dropSpots);
					var object = ui.draggable.clone();
					object.draggable('disable');
					
					// alert(ui.draggable.attr('dropSpots')[currentId] + " ,"+ui.draggable.attr('targetCount'));

					//object.css({position:'relative'});
					if(count==0) separator=""; else if(count%2==0) separator=",<br/><br/>"; else separator=", ";
					count++;
					$(this).append(separator)
					$(this).append(object);

					
					if(dropCount == targetCount)
						ui.draggable.draggable('disable').addClass('used');
								// 
								// ui.draggable.attr('dropCount', dropCount);
								// var object = ui.draggable.clone();
								// object.draggable('disable');
								// // alert(ui.draggable.attr('dropCount')+ " ,"+ui.draggable.attr('targetCount'));
								// 
								// //object.css({position:'relative'});
								// if(count==0) separator=""; else if(count%2==0) separator=",<br/><br/>"; else separator=", ";
								// count++;
								// $(this).append(separator)
								// $(this).append(object);
								// 
								// lastFound=true;
								// if(dropCount == targetCount){
								// 	ui.draggable.draggable('disable').addClass('used');
				}
				//$(ui).attr('found', 'true');
			}
		})
	});
}


/**************************************
// drag and drop onto image
/**************************************/
initImageDrop = function(){
	
	$('map').each(function(){
		var mapid = $(this).attr("name");
		var imgOffset;
		$("img[usemap='#" + mapid + "']").each(function(){
			 // var top = Math.max(docElem.scrollTop, body.scrollTop); 
			 // imgOffset = ObjectPosition($(this).get());
			imgOffset= $(this).offset();
		});
		
		$('area', this).each(function(){
			var coords = $(this).attr('coords').split(",");
			var id= $(this).attr('id');
			
			appendArea(imgOffset, {"x1": coords[0], "y1":coords[1],"id":id, "withClass": "note drop-camo"});
		});

	});
	$('map').remove();
}

function appendArea(imgOffset, note_data ){
	
	note_left  = parseInt(imgOffset.left) + parseInt(note_data.x1);
	note_top   = parseInt(imgOffset.top) + parseInt(note_data.y1);
	index = parseInt(note_data.pos);
	note_p_top = note_top + parseInt(note_data.height)+5;
					
	note_area_div = $("<div class='"+ note_data.withClass + "'></div>")
			.css({ left: note_left + 'px', top: note_top + 'px'})
			.attr({id: note_data.id}).addClass( index==0 ? "ball-back" : "ball-fore");
	
	// alert("index:"+ index);

	$('#global').append(note_area_div);
}

initOnImageDrop = function(){
	
	$('map').each(function(){
		var mapid = $(this).attr("name");
		var imgOffset;
		$("img[usemap='#" + mapid + "']").each(function(){
			 imgOffset = $(this).offset();// + getScrollHeight();
		});
		
		$('area', this).each(function(){
			var coords = $(this).attr('coords').split(",");
			var id= $(this).attr('id');
			
			var blockId= "gap"+id.split("d-t")[1];
			// debugThis(coords[0]+ " "+ coords[1]);
			appendBlock(imgOffset, blockId, {"x1": coords[0], "y1":coords[1],"id":id, "withClass": "note"});
		});

	});
	$('map').remove();
}

function appendBlock(imgOffset, blockid, note_data ){
	note_left  = parseInt(imgOffset.left) + parseInt(note_data.x1);
	note_top   = parseInt(imgOffset.top) + parseInt(note_data.y1);
	index = parseInt(note_data.pos);
	note_p_top = note_top + parseInt(note_data.height)+5;
					
	note_area_div = $("<div class='"+ note_data.withClass + "'></div>")
			.html( $('#'+blockid))
			.css({ left: note_left + 'px', top: note_top + 'px'})
			.attr({id: note_data.id});
			//.addClass( index==0 ? "ball-back" : "ball-fore");
	
	// alert("index:"+ index);

	$('#global').append(note_area_div);
}


/**************************************
// spelling and correction
/**************************************/

initCheckSpelling = function(){
        for(var key in arrayAns){
                var tmp_array= key.split(" "); //gives an array with 2+ items : key value
                arrayAnsDrop[tmp_array[1]] = tmp_array[0];
        }
        
        
        $(".gap").each( function(){
                var pos = $('.positive', this).html();
                var neg = $('.negative', this).html();
                var ans = (arrayAnsDrop[ $(':input', this).attr('id') ] ).toLowerCase();
                var key = $(this).attr("id");
                
                var nearmatched=false;
                var corrected=false;
                
                $("input", this).blur(function(){
                      var guess = this.value.toLowerCase() ;
	                  var repiece = guess.replace(/\ /g,"_");
	                  nearmatched=false;

	                  if(guess == ans || guess.split(" ")[0]==ans || repiece == ans){
	                          doSuccess($(this));
	                          feedback(pos, true);
	                          watchAnswerGroups();
	                          corrected=true;
	                  }
	                  else if( $(this.parent).find(".nearmatch").length>0){
	                          $(this.parent).find(".nearmatch").each(function(){
	                                  //debugThis($(this).attr("id"));
	                                  if(guess == $(this).attr('id') ){
	                                          doFail($(this));
	                                          feedback($(this).text(), false);
	                                          nearmatched=true;
	                                  }
	                          });
	                  }

	                  if(!nearmatched && !corrected && guess.length>0){
	                          /*if(compareStrings(ans, guess) == ans){
	                                  this.value= ans;
	                                  doSuccess($(this));
	                                  feedback(pos, true);
	                          }
	                          else{*/
	                                  var replacedText ="";
	                                  for( var i = 0; i< ans.length; i++){
	                                          if( guess.charAt(i)==ans.charAt(i) || apostropheHelper(guess.charAt(i),ans.charAt(i))){
	                                                  replacedText +=ans.charAt(i);
	                                          }
											else if (ans.charAt(i) == "_"){
												replacedText +=" ";
											}
	                                          else{
	                                                  replacedText +="*";
	                                          }
	                                  }
	                                  this.value=replacedText;
	                                  doFail($(this));
	                                  feedback(neg, false);
	                          //}
	                  }
	                  else if(!nearmatched && !corrected && this.value.length< ans.length - 1){

	                  }
	                  else if(!nearmatched && !corrected){ 
	                          doFail($(this));
	                          feedback(neg, false);
	                  }
	          });
                
                $(':input', this).keyup(function(){
                        var guess = this.value.toLowerCase() ;
                        var repiece = guess.replace(/\ /g,"_");
                        nearmatched=false;
						corrected=false;
                        
                        if(guess == ans || guess.split(" ")[0]==ans || repiece == ans){
                                doSuccess($(this));
                                feedback(pos, true);
                                watchAnswerGroups();
                                corrected=true;
                        }

						
						else if( $(this.parent).find(".nearmatch").length>0){
							$(this.parent).find(".nearmatch").each(function(){
								//debugThis($(this).attr("id"));
								if(guess == $(this).attr('id') ){
									doFail($(this));
									feedback($(this).text(), false);
									nearmatched=true;
								}
							});
						}
                        
						if(!nearmatched && !corrected && guess.length >= ans.length + 2){

							var replacedText ="";
							for( var i = 0; i< ans.length; i++){
								if( guess.charAt(i)==ans.charAt(i) || apostropheHelper(guess.charAt(i),ans.charAt(i))){
									replacedText +=ans.charAt(i);
								}
								else if (ans.charAt(i) == "_"){
									replacedText +=" ";
								}
								else{
									replacedText +="*";
								}
							}
							this.value=replacedText;
							//}
						}
						else if(!corrected && Math.abs(guess.length - ans.length) <= 1){
							doFail($(this));
						}
												// 
												// else if(guess.length > ans.length){
												// 	doFail($(this));
												// 	                        feedback(neg, false);
												// }
                });
        });
        
}

apostropheHelper = function(guess, ans){
	// alert("called");
	if ( guess == "’" || guess == "'" || guess =="`" && ans == "’" || ans == "'" || ans =="`") return true;
	else return false;
}


compareStrings = function(answer, guess){
	// similarity check algorythm
    var i = 0;
    var j = 0;
    var orders = [[answer, guess], [guess, answer]];
    var maxMisses = Math.floor(answer.length / 6) + 1;
    var misses = 0;
    if (guess.length <= maxMisses) {
        misses = Math.abs(guess.length - answer.length);
        for (i = 0; i < guess.length; i++ ) {
            if (answer.search(guess[i]) == -1) {
                misses += 1;
            }
        }
        if (misses <= maxMisses) {
            return answer;
        } else {
            return guess;
        }
    }
    // Iterate through the different orders of checking
    for (i = 0; i < 2; i++) {
        var string1 = orders[i][0];
        var string2 = orders[i][1];
        while (string1) {
            misses = Math.floor(
                        (Math.abs(string1.length - string2.length) +
                         Math.abs(guess.length - answer.length)) / 2)
            var max = Math.min(string1.length, string2.length)
            for (j = 0; j < max; j++) {
                var a = string2.charAt(j);
                var b = string1.charAt(j);
                if (a != b)
                    misses += 1;
                if (misses > maxMisses)
                    break;
            }
            if (misses <= maxMisses)
                // You are right
                return answer;
            string1 = string1.substr(1);
        }
    }
    // You are wrong!
    return guess;
}

correctSpelling = function(){
	arrayAnsDrop = {};
	for(var key in arrayAns){
		var tmp_array= key.split(" "); //gives an array with 2+ items : key value
		arrayAnsDrop[tmp_array[1]] = tmp_array[0];
	}
	
	for(var key in arrayAnsDrop){
		if(	!$("#"+key).is('.success')){
			$("#"+key).parent().text(arrayAnsDrop[key].replace(/_/g," ")).addClass('corrected');
		}
		
		//$("#"+key).remove();
	}
	
}

/**************************************
// matching
/**************************************/

initMatching = function(){
	
	$('.matchbox').append("<div class='matchboxleft'></div><div id='answergroup' class='matchboxright'></div>");
	
	$('div.matchstart').each( function(){
		var clone= $(this).clone();
		$(clone).appendTo('.matchboxleft');
		// $(this).addClass("invisible");
		$(this).remove();
		
		$(clone).click(function(ev){
			clickOn=true;
			clickFlag = $(this).attr('id');
			clickObj = $(this);
			$('.matchstart').removeClass('selected');
			$(this).addClass('selected');
			
			mouseX = ev.pageX;
			mouseY = ev.pageY;
		})
	});
	
	$('.matchend').each(function(){
		var clone= $(this).clone();
		$(clone).appendTo('.matchboxright');
		//$(this).addClass("invisible");
		$(this).remove();
		
		var itemIncorrect = "incorrect" + clickFlag;
		
		$(clone).click(function(ev){
			if(clickOn){
				$('.matchstart').removeClass('selected');
				clickOn =false;
				$("#"+itemIncorrect).remove();
				// alert( "-"+arrayAnsDrop[$(this).attr('id')]+"-" );
				// alert("-"+clickFlag+"-");
				var possibilities = arrayAnsDrop[$(this).attr('id')].split(" ");
				for( var i = 0; i< possibilities.length; i++){
					if( possibilities[i] == clickFlag ){
						$('body').drawPolyline([mouseX, ev.pageX ], [mouseY,ev.pageY], {color:'#48D647', alpah:1});
						$(this).addClass('found');
						$(clickObj).addClass('found');
						$(clickObj).click(function(){});
					}
					else{
						$(this).append("<div id='"+itemIncorrect+"'></div>");
						$("#"+itemIncorrect).drawPolyline([mouseX, ev.pageX ], [mouseY,ev.pageY], {color:'#D64720', alpah:1});
					}
				}
			}
			else{

			}
			watchAnswerGroups();
		})
	});
	
	$('.matchboxleft').children().sort(function(a, b) { 
		var rand=Math.floor(Math.random()*2) - Math.floor(Math.random()*2);
		return rand;
		}).prependTo('.matchboxleft'); 

	$('.matchboxright').children().sort(function(a, b) { 
		var rand=Math.floor(Math.random()*2) - Math.floor(Math.random()*2);
		return rand;
		}).prependTo('.matchboxright');
	
}

correctMatching = function(){
	// alert("correcting matches");
	$(".matchstart").each(function(){
		var blockid = $(this).attr("id");
		var ans = arrayAnsToDrop[blockid].split("&");
		
		for(var i=0; i<ans.length; i++){
			var end= ans[i];
			
			startx = $("#"+blockid).offset().left + $("#"+blockid).width()/2;
			starty = $("#"+blockid).offset().top + $("#"+blockid).height()/2;
			endx = $("#"+end).offset().left + $("#"+end).width()/2;
			endy = $("#"+end).offset().top + $("#"+end).height()/2;
			// alert("startx :"+startx + ", starty :"+ starty);
			$('body').drawPolyline([startx, endx ], [starty,endy], {color:'#48D647', alpah:1});
			$("#"+blockid + " ,#"+end).addClass("red");
		}
		
	});
	
	// for (var blockgroups in arrayAnsToDrop){
	// 		// debugThis(blockgroups, 10);
	// 		var blockids = blockgroups.split("&");
	// 		
	// 		for( var i= 0; i<blockids.length; i++){
	// 			var blockid=blockids[i];
	// 			// debugThis(blockid,10);
	// 			if(blockid != ""){
	// 				var end = arrayAnsToDrop[blockid];
	// 				// alert(blockid+" "+end);
	// 				startx = $("#"+blockid).offset().left + $("#"+blockid).width()/2;
	// 				starty = $("#"+blockid).offset().top + $("#"+blockid).height()/2;
	// 				endx = $("#"+end).offset().left + $("#"+end).width()/2;
	// 				endy = $("#"+end).offset().top + $("#"+end).height()/2;
	// 				// alert("startx :"+startx + ", starty :"+ starty);
	// 				$('body').drawPolyline([startx, endx ], [starty,endy], {color:'#48D647', alpah:1});
	// 				$("#"+blockid + " ,#"+end).addClass("red");
	// 			}
	// 		}
	// 	}
}


/********************
*******GROUP SENSE*******
***************************/

initGroupSense  = function(){
	$('.senseseparator').each(function(){
		var fbt = $('.feedback', this).html();
		var state=$('.feedback', this).attr("name");
		
		$(this).append("&nbsp;&nbsp;")
			.click(function(){
				if(state=="true"){
					$(this).html("/").addClass("senseseparator-found");
					feedback(fbt, true);
					watchAnswerGroups();
				}
				else feedback(fbt, false);                                                             	
		});
	});
}

correctGroupSense = function(){
	$('.senseseparator').each(function(){
		var state=$('.feedback', this).attr("name");
		if(state=="true"){
			$(this).html("/").addClass("senseseparator-corrected");
		}
	});
}


/********************
*******STRESSED VOWEL*******
***************************/

initStressedVowel  = function(){
	$('.stressedvowel').each(function(){
		var fbt = $('.feedback', this).html();
		var state=$('.feedback', this).attr("name");
		
		$(this)
			.click(function(){
				if(state=="true"){
					$('.content',this).addClass("stressedvowel-found");
					feedback(fbt, true);
					watchAnswerGroups();
				}
				else feedback(fbt, false);                                                             	
		});
	});
}

correctStressedVowel = function(){
	$('.stressedvowel').each(function(){
		var state=$('.feedback', this).attr("name");
		if(state=="true"){
			$(this).addClass("stressedvowel-corrected");
		}
	});
}

/********************
*******FIND WORDS*******
***************************/

findWord = function(){
	$(".findme").each(function(){
		$(this).hover(function(){
			$(this).addClass("found");
		});
	});
}

correctFindWord = function(){
	$(".findme:not('.found')").addClass("corrected");
}


/********************
*******CORRECTION*******
***************************/


initCorrection = function(){
	$("#correct").submit(function(){
		if(!appliedCorrection){
			if(isExoType("fill-in")){
				correctSpelling();
			}
			if(isExoType("inline")){
				correctInline();
			}
			if(isExoType("multipleChoice")){
				correctMultiChoice();
			}
			if(isExoType("directedPair") 
			|| isExoType("tableSort") || isExoType("directedPairMatching")
			|| isExoType("imageMatch") || isExoType("directedPairAbacus") 
			|| isExoType("onImageMatch")) {
				correctDrop();
				watchAnswerGroups();
			}
			if(isExoType("matching")){
				correctMatching();
			}
			if(isExoType("directedMatch")){
				correctMultiDrop();
				watchAnswerGroups();
			}
			if(isExoType("groupsense")){
				correctGroupSense();
				watchAnswerGroups();
			}
			if(isExoType("stressedvowel")){
				correctStressedVowel();
				watchAnswerGroups();
			}
			if(isExoType("findWords")){
				correctFindWord();
				watchAnswerGroups();
			}
			appliedCorrection=true;
		}
		return false;
	});
}

initVerification = function(){
		$("#verification").submit(function(){
			finalFeedback();
			return false;
		});
	
}

/**************************************
// flash external file (lang) parametering
/**************************************/

function getSWF(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
	return window[movieName];
	} else {
	return document[movieName];
	}
}

isReady = function(){
	return true;
}
initParamFlash = function(){
	// $('.flash-media').each(function(){
	// 	var filename= $(this).attr("name");
	// 	var flashobj = $('object', this).attr('id');
	// 	
	// 	//getSWF(flashobj).setLangFile("http://localhost/babel-data/flash/"+filename);
	// 
	// 	$('#flash-start').click(function(){
	// 		getSWF(flashobj).setLangFile("http://localhost/babel-data/flash/"+filename);
	// 	});
	// });
	
}

/**************************************
// helpers
/**************************************/

doSuccess = function(theobject){
	$(theobject).addClass('success');
	$(theobject).removeClass('fail');
}

doFail = function(theobject){
	$(theobject).addClass('fail');
	$(theobject).removeClass('success');
}

doNeutral = function(theobject){
	$(theobject).removeClass('fail');
	$(theobject).removeClass('success');
}


jQuery.fn.alternateRowColors = function() { 
  $('tbody tr:odd', this).removeClass('even').addClass('odd'); 
  $('tbody tr:even', this).removeClass('odd').addClass('even'); 
  return this; 
}; 


initTableSort = function(){
	$('table.sortable').each(function() { 
		//$(this).css({ float:'left'});
   		var $table = $(this); 
		var rows = $table.find('tbody > tr').get(); 

		$.each(rows, function(index, row) { 
		  row.sortKey = $(row).children('td').text().toUpperCase(); 
		}); 
		
		rows.sort(function(a, b) { 
		  if (a.sortKey < b.sortKey) return -1; 
		  if (a.sortKey > b.sortKey) return 1; 
		  return 0; 
		}); 
		
		$.each(rows, function(index, row) { 
		  $table.children('tbody').append(row); 
		  row.sortKey = null; 
		}); 
		
		jQuery.fn.alternateRowColors($table); 

	});
}

/**************************************
// debug helpers
/**************************************/

debugThis = function(item, times){
	var times = (times==null)? 1 : times;
	if(!debugHelper && debugDispCount<times){
		debugDispCount++;
		if(debugDispCount == times)
			debugHelper = true;
		alert("-:"+item+":-");
	}
}


/************ extensions ***********/

jQuery.fn.contains = function(txt) { return jQuery(this).indexOf(txt) > 0; }



/******** SCROLL **************/
function getScrollHeight()
{
   var h = window.pageYOffset ||
           document.body.scrollTop ||
           document.documentElement.scrollTop;
           
   return h ? h : 0;
}
